__author__ = 'zoulida'
from functools import lru_cache

from tools.timeTools import daystrTodaystr


def getPro():
    import tushare as ts
    pro = ts.pro_api('69d6b836725cd75df21b39873603b14fed58d101bc033b991b51eb41')
    return pro

@lru_cache()
def getCal_dates():#获取交易日历
    pro = getPro()

    cal_dates2 = pro.trade_cal(exchange='')
    #cal_dates2 = pro.query('trade_cal')
    print(cal_dates2)

    return cal_dates2


def is_open_day(date= '20200308'):
    # print(cal_dates[cal_dates['calendarDate'] == date])
    cal_dates = getCal_dates()
    if date in cal_dates['cal_date'].values:
        return cal_dates[cal_dates['cal_date'] == date].iat[0, 2] == 1
    return False

def getOpenDayNum(start = '20220101',end = '20230227'):
    char1 = '-'
    if char1 in end:
        end = daystrTodaystr(end)
    if char1 in start:
        start = daystrTodaystr(start)
    cal_dates = getCal_dates()
    rangedates = cal_dates.query('\'%s\' <= cal_date <= \'%s\''%(start,end))
    isopendays = rangedates[rangedates['is_open'] == 1]
    #isopendays = rangedates.query('is_open = 1')
        #cal_dates[cal_dates['cal_date'] >= start and cal_dates['cal_date'] <= end]
    #print(isopendays)

    return len(isopendays)


def getLastOpenDay(date):
    cal_dates = getCal_dates()
    lastDay = cal_dates[cal_dates['cal_date'] == date].iat[0, 3]
    return lastDay

def spot():
    pro = getPro()
    #df = pro.daily(ts_code='600519.SH', start_date='20200708', end_date='20200709')#这个可以获取任意时间任意股票的数据，但可能有行数限制
    df = pro.daily()
    print(df)
if __name__ == '__main__':
    #bl = is_open_day('20200308')
    #bl = getLastOpenDay('20230222')
    #print(bl)
    #num = getOpenDayNum(start = '2022-01-01',end = '2023-02-27')
    #print(num)
    #spot()
    getCal_dates()